package com.curry.android.core;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.HttpClient;

import android.util.Log;

import java.util.HashMap;
import java.util.Map;

@Deprecated
public class JsonHttpServlet implements IHttpServlet {

    private String url;
    private String params;
    private HashMap<String, String> header;
    private boolean isDebug;
    private boolean isHeaderDebug;
    private static final int TIMEOUT_CONNECTION = 30000;

    /**
     * JsnHttoServlet 构造函数
     *
     * @param url 地址
     */
    public JsonHttpServlet(String url, HashMap<String, String> header, boolean isDebug, boolean isHeaderDebug) {
        this.isDebug = isDebug;
        if (isDebug) {
            Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 url = " + url);
        }
        this.url = url;
        this.header = header;
        if (isHeaderDebug) {
            if (header != null) {
                if (isHeaderDebug) {
                    Log.e(JsonHttpServlet.class.getSimpleName(), "JHS header = " + header.toString());
                }
            } else {
                Log.e(JsonHttpServlet.class.getSimpleName(), "Note : JHS header is null ");
            }
        }
    }

    /**
     * JsnHttoServlet 构造函数
     *
     * @param url    地址
     * @param params JSON封装的数据源
     */
    public JsonHttpServlet(String url, HashMap<String, String> header, String params, boolean isDebug, boolean isHeaderDebug) {
        this.isDebug = isDebug;
        if (isDebug) {
            Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 url = " + url);
        }
        this.url = url;
        this.header = header;
        this.params = params;
        if (isHeaderDebug) {
            if (header != null) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS : url = " + url + " , header = " + header.toString());
            } else {
                Log.e(JsonHttpServlet.class.getSimpleName(), "Note : JHS header is null ");
            }
        }
    }

    /**
     * 为HTTP请求统一添加头部
     * by wgf
     *
     * @param request
     * @since v3.8
     */
    private void addHeader(HttpRequestBase request) {
        if (header != null) {
            if (request != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }
        } else {
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "Http Header is null!!!");
            }
        }
    }

    /**
     * HttpPost 提交数据
     */
    @Override
    public HttpConnStatus post() {
        HttpPost httpPost = new HttpPost(url);
        addHeader(httpPost);
        try {
            // StringEntity entity = new StringEntity(params, "utf-8");
            // httpPost.setEntity(entity);
            if (params == null || "".endsWith(params)) {
                return response(httpPost);
            } else {
                return response(httpPost, params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            HttpConnStatus hcs = new HttpConnStatus();
            hcs.setCode(1000);
            hcs.setDescribe(statusCodeDes(1000));
            return hcs;
        }
    }

    /**
     * HttpGet 提交数据
     */
    @Override
    public HttpConnStatus get() {
        try {
            return Http2Get();
        } catch (Exception e) {
            e.printStackTrace();
            HttpConnStatus hcs = new HttpConnStatus();
            hcs.setCode(1000);
            hcs.setDescribe(statusCodeDes(1000));
            return hcs;
        }
    }

    /**
     * @param httpPost
     * @param params
     * @return result
     * @throws Exception
     */
    public HttpConnStatus response(HttpPost httpPost, String params) throws Exception {
        HttpConnStatus hcs = new HttpConnStatus();
        BasicHttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter("charset", "utf-8");
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_CONNECTION);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_CONNECTION);
        HttpClient httpclient = new DefaultHttpClient(httpParams);
        StringEntity s = new StringEntity(params, "utf-8");
        s.setContentType("application/json");
        httpPost.setEntity(s);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            String responseBody = EntityUtils.toString(httpResponse.getEntity());
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 request ok , 200 ,response = " + responseBody);
            }
            hcs.setCode(statusCode);
            hcs.setDescribe(responseBody);
        } else {
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 request fail , errCode = " + statusCode);
            }
            hcs.setCode(statusCode);
            hcs.setDescribe(statusCodeDes(statusCode));
        }

        return hcs;
    }

    /**
     * @param httpPost
     * @return result
     * @throws Exception
     */
    private HttpConnStatus response(HttpPost httpPost) throws Exception {
        String result = "";
        HttpConnStatus hcs = new HttpConnStatus();
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);//连接时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_CONNECTION);//数据传输时间
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
            /* Log.i(TAG, result);*/
            hcs.setCode(statusCode);
            hcs.setDescribe(result);
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 request ok , 200 ,response = " + result);
            }
        } else {
            hcs.setCode(statusCode);
            hcs.setDescribe(statusCodeDes(statusCode));
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 request fail , errCode = " + statusCode);
            }
        }

        return hcs;
    }

    /**
     * @return result
     * @throws Exception
     */

    private HttpConnStatus Http2Get() throws Exception {
        String result = "";
        HttpConnStatus hcs = new HttpConnStatus();
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);//连接时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_CONNECTION);//数据传输时间
        HttpGet httpGet = new HttpGet(url);
        addHeader(httpGet);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        /* Log.e(TAG, "execute");*/
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 request ok , 200 ,response = " + result);
            }
            hcs.setCode(statusCode);
            hcs.setDescribe(result);
        } else {
            hcs.setCode(statusCode);
            hcs.setDescribe(statusCodeDes(statusCode));
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 request fail , errCode = " + statusCode);
            }
        }
        return hcs;

    }


    @Override
    public HttpConnStatus put() {
        HttpPut httpPut = new HttpPut(url);
        addHeader(httpPut);
        try {
            // StringEntity entity = new StringEntity(params, "utf-8");
            // httpPost.setEntity(entity);
            if (params == null || "".endsWith(params)) {
                return response(httpPut);
            } else {
                return response(httpPut, params);
            }
        } catch (Exception e) {
            e.printStackTrace();
            HttpConnStatus hcs = new HttpConnStatus();
            hcs.setCode(1000);
            hcs.setDescribe(statusCodeDes(1000));
            return hcs;
        }

    }


    public HttpConnStatus response(HttpPut httpPut, String params) throws Exception {
        HttpResponse httpResponse = null;

        String responseBody = "500";
        HttpConnStatus hcs = new HttpConnStatus();
        BasicHttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter("charset", "utf-8");
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_CONNECTION);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_CONNECTION);

        HttpClient httpclient = new DefaultHttpClient(httpParams);
        /* Log.e(TAG, params); */
        StringEntity s = new StringEntity(params, "utf-8");
        s.setContentType("application/json");
        httpPut.setEntity(s);

        httpResponse = httpclient.execute(httpPut);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            responseBody = EntityUtils.toString(httpResponse.getEntity());
            hcs.setCode(statusCode);
            hcs.setDescribe(responseBody);
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 request ok , 200 ,response = " + responseBody);
            }
        } else {
            hcs.setCode(statusCode);
            hcs.setDescribe(statusCodeDes(statusCode));
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 request fail , errCode = " + statusCode);
            }
        }

        return hcs;
    }

    /**
     * @return result
     * @throws Exception
     */
    private HttpConnStatus response(HttpPut httpPut) throws Exception {
        String result = "";
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpPut);
        HttpConnStatus hcs = new HttpConnStatus();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
            /* Log.i(TAG, result);*/
            hcs.setCode(statusCode);
            hcs.setDescribe(result);
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 request ok , 200 ,response = " + result);
            }
        } else {
            hcs.setCode(statusCode);
            hcs.setDescribe(statusCodeDes(statusCode));
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 request fail , errCode = " + statusCode);
            }
        }

        return hcs;
    }

    @Override
    public HttpConnStatus delete() {
        HttpDelete httpDelete = new HttpDelete(url);
        addHeader(httpDelete);
        HttpConnStatus hcs = new HttpConnStatus();
        try {
            // StringEntity entity = new StringEntity(params, "utf-8");
            // httpPost.setEntity(entity);
            return response(httpDelete);
        } catch (Exception e) {
            e.printStackTrace();

            hcs.setCode(1000);
            hcs.setDescribe(statusCodeDes(1000));
            return hcs;
        }

    }


    /**
     * @return result
     * @throws Exception
     */
    private HttpConnStatus response(HttpDelete httpdel) throws Exception {
        String result = "";
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);//连接时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_CONNECTION);//数据传输时间
        HttpResponse httpResponse = httpClient.execute(httpdel);
        HttpConnStatus hcs = new HttpConnStatus();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
            /* Log.i(TAG, result);*/
            hcs.setCode(statusCode);
            hcs.setDescribe(result);
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS3 request ok , 200 ,response = " + result);
            }
        } else {
            hcs.setCode(statusCode);
            hcs.setDescribe(statusCodeDes(statusCode));
            if (isDebug) {
                Log.e(JsonHttpServlet.class.getSimpleName(), "JHS2 request fail , errCode = " + statusCode);
            }
        }

        return hcs;
    }

    private String statusCodeDes(int statusCode) {
        String str = null;
        switch (statusCode) {
            case 400:
                str = "客户端请求有语法错误，不能被服务器所理解";
                break;
            case 401:
                str = "请求未经授权，这个状态代码必须和WWW-Authenticate报头域一起使用";
                break;
            case 403:
                str = "服务器收到请求，但是拒绝提供服务";
            case 404:
                str = "请求资源不存在，eg：输入了错误的URL";
            case 500:
                str = "服务器发生不可预期的错误";
            case 503:
                str = "服务器当前不能处理客户端的请求，一段时间后可能恢复正常";
            case 1000:
                str = "网络连接失败";
            case 1001:
                str = "请用URL方式提交";
            default:
                str = "服务器发生不可预期的错误";
                break;
        }
        return str;
    }


}
